<template>
	<view class="container">
		<!-- 顶部固定区 -->
		<view class="fixed-view">
			<!-- 账户总览 -->
			<view class="page-top">
				账户总览
			</view>
			<!-- 账户列表 -->
			<view class="des-account">
				<view class="account-total">
					<text :class="['account-total-money', gteq(account_total,'0') ? 'money-green':'money-red' ]">
						{{ gteq(account_total,'0') ? ('￥' + formatMoney(account_total)) : ('-￥' + formatMoney(account_total.replace('-',''))) }}
					</text>
					<text class="data-more" @click="goCashLogYear">资金趋势</text>
				</view>
				<view class="account-total-des">
					<text :class="['account-total-des-cx', 'money-green' ]">
						{{ '资产 ￥' + formatMoney(account_total_cx)}}
					</text>
					<text :class="['account-total-des-xy', 'money-red' ]">
						{{ '负债 -￥' + formatMoney(account_total_xy.replace('-','')) }}
					</text>
				</view>
				<qiun-data-charts style="height: 220rpx;" type="area" :opts="opts" :chartData="chartData"
					:ontouch="true" :onmovetip="true" :loadingType="0" :tapLegend="false"
					tooltipFormat="myTooltip_month" />
			</view>
		</view>

		<!-- 内容区 -->
		<scroll-view class="content-view-scroll" scroll-y>
			<!-- 账户列表 储蓄卡 -->
			<view class="account-list">
				<view class="account-list-title">
					<view class="account-list-title-left">储蓄卡</view>
				</view>
				<view class="account-list-item" v-for="item, index in account_list_1" :key="index"
					@click="openAccountDialog(item)">
					<view class="account-list-item-content">
						<view class="account-name">
							<image class="account-name-icon" mode="aspectFit" :src="item.icon"></image>
							<text>{{ item.name }}</text>
							<text v-if="item.status == 2" class="money-red">( 冻结中 )</text>
						</view>
						<view class="money-green">
							{{'￥' + formatMoney(item.money)}}
						</view>
					</view>
				</view>
			</view>
			<!-- 账户列表 信用卡 -->
			<view class="account-list account-list2">
				<view class="account-list-title">
					<view class="account-list-title-left">信用卡</view>
				</view>
				<view class="account-list-item" v-for="item, index in account_list_2" :key="index"
					@click="openAccountDialog(item)">
					<view class="account-list-item-content">
						<view class="account-name">
							<image class="account-name-icon" mode="aspectFit" :src="item.icon"></image>
							<text>{{ item.name }}</text>
							<text v-if="item.status == 2" class="money-red">( 冻结中 )</text>
						</view>
						<view class="money-red">
							{{ eq(item.money, 0) ? ('￥' + formatMoney(item.money.replace('-',''))) : ('-￥' + formatMoney(item.money.replace('-',''))) }}
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 悬浮按钮 -->
		<zjw-float-button label="+" width="120rpx" bgColor="rgba(7, 193, 96, 1)" @click="openAccountDialog">
		</zjw-float-button>

		<!-- 普通弹窗：添加账户 -->
		<uni-popup ref="accountDialog" type="center" :is-mask-click="true" @maskClick="cancelSaveAccountData"
			:animation="true">
			<view class="accountDialog-page">
				<view class="accountDialog-top">
					<view class="accountDialog-title">{{ accountDialogTitle }}</view>
					<view class="accountDialog-opt">
						<uni-icons v-if="showDelete" type="trash" size="22" color="#ffffff"
							@click="delAccount"></uni-icons>
					</view>
				</view>
				<view class="accountDialog-content">
					<!-- 分类 -->
					<zjw-button-group class="type-group" v-model="accountDialogForm.type" :buttons="account_type_list"
						bt-class="type-group-button" bt-select-class="type-group-button-act"
						:disabled="accountDialogTypeDisabled">
					</zjw-button-group>
					<!-- 账户名称 -->
					<view class="accountDialog-content-name">
						<text class="name-label">账户名称</text>
						<view class="name-input-view">
							<image class="name-input-icon" mode="aspectFit" :src="accountDialogForm.icon"
								@click="openSelectDialog">
							</image>
							<input class="name-input" :focus="accountDialogForm.id == 0"
								v-model="accountDialogForm.name" placeholder-class="name-input-place"
								placeholder="点击输入账户名称" :disabled="accountDialogNameDisabled" />
						</view>
					</view>
					<!-- 金额 -->
					<view class="accountDialog-content-money" @click="openCalculator()">
						<text class="money-label">金额</text>
						<view class="line-money">
							<text :class="['money-icon', accountDialogForm.type == 1 ? 'money-green':'money-red']">
								{{accountDialogForm.type == 1 ? '￥' : '-￥'}}
							</text>
							<text :class="['money-content', accountDialogForm.type == 1 ? 'money-green':'money-red']">
								{{ formatMoney(accountDialogForm.money) }}
							</text>
						</view>
					</view>
					<!-- opt -->
					<view class="accountDialog-content-btns">
						<button class="btn-save" @click="saveAccountData">保 存</button>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 通用选择器 -->
		<zjw-list-popup :title="selectDialog_Title" ref="selectDialog" :data="selectDialog_data"
			@click="confirmSelected">
		</zjw-list-popup>

		<!-- 计算器组件 -->
		<zjw-calculator ref="myCalculator" :initNumber="calculatorInitNumber" @confirm="confirmCalculator"
			@cancel="cancelCalculate">
		</zjw-calculator>
	</view>
</template>

<script setup>
	import {
		onUnmounted,
		ref
	} from 'vue'
	import {
		onPullDownRefresh,
		onShow,
		onBackPress
	} from '@dcloudio/uni-app'
	import {
		getNowMonth,
		formatMoney
	} from '@/utils/utils.js'
	import {
		deleteAccount,
		getAccountMoneyTotalForMonth,
		getAllAccountList,
		saveAccount,
		updateAccountTotalForName
	} from '@/service/service-api.js'
	import {
		gt,
		lt,
		gteq,
		lteq,
		eq,
		negate
	} from '@/utils/math-utils'
	import {
		getBankIconList
	} from '@/utils/bank-icon-utils'

	const opts = ref({
		color: ["#07C160", "#1890FF", "#91CB74", "#FAC858", "#73C0DE", "#3CA272", "#9A60B4", "#ea7ccc"],
		padding: [5, 20, 0, 10],
		xAxis: {
			axisLineColor: "transparent",
			disabled: false, // 是否禁止绘制x轴
			disableGrid: true, // 是否禁止显示网格线
			labelCount: 7, // 单屏幕数据点文字（刻度点）限制显示的数量
			fontSize: 10,
			fontColor: "#07C160"
		},
		yAxis: {
			data: [{
				// min: 0, // 最小刻度值，不写默认数据中的最小值
				axisLineColor: "transparent",
				axisLine: false, //坐标轴轴线是否显示（数据还能显示） 默认true
				disabled: true, // 是否禁止绘制y轴
				fontSize: 10,
				fontColor: "#07C160"
			}],
			disableGrid: true, // 是否禁止显示网格线
		},
		dataLabel: false, // 是否显示面板数据
		dataPointShape: false, // 是否显示数据点的图形标识
		dataPointShapeType: 'solid', //图形标识点显示类型，可选值：'solid'实心,'hollow'空心
		legend: {
			show: false, // 隐藏图例名称
		},
		enableScroll: false,
		enableMarkLine: true,
		extra: {
			tooltip: {
				// 开启跟手显示tooltip功能（前提条件，1、需要开启touch功能，即:ontouch="true"；2、并且opts.enableScroll=false即关闭图表的滚动条功能）
				showArrow: false, // 是否显示旁边的小三角箭头
				bgColor: '#ffffff',
				bgOpacity: 0.5,
				fontColor: '#07C160',
				fontSize: 10,
				lineHeight: 14,
				borderRadius: 4,
				splitLine: true, // 是否显示垂直竖线
				horizentalLine: false, // 是否显示水平横线
				gridColor: '#07C160', // 竖线颜色
				gridType: 'dash', // 线型，可选值：'solid'实线,'dash'虚线
				dashLength: 6, // 虚线长度 默认 4
				legendShow: false // 是否显示左侧图例图标
			},
			markLine: {
				type: 'dash', // 标记线线型，可选值：'solid'实线,'dash'虚线
				dashLength: 4, // 单段虚线长度
				data: [{
					value: 0
				}]
			},
			area: { // 区域图配置
				type: "curve", // 区域图类型，可选值："straight"尖角折线模式,"curve"曲线圆滑模式,"step"时序图模式
				opacity: 0.2, // 区域图透明度
				addLine: true, // 是否叠加相应的折线
				width: 2, // 叠加的折线宽度
				gradient: true, // 是否开启区域图渐变色
				activeType: "none" // 激活指示点类型，可选值："none"不启用激活指示点,"hollow"空心点模式,"solid"实心点模式
			}
		}
	}) // 图表配置
	const chartData = ref({}) // 图表数据
	const account_total = ref('0') // 图表数据_净资产
	const account_total_cx = ref('0') // 图表数据_资产
	const account_total_xy = ref('0') // 图表数据_负债
	const account_list_1 = ref([]) // 账户列表 1 储蓄卡
	const account_list_2 = ref([]) // 账户列表 2 信用卡
	const accountDialog = ref(null) // 弹出层：创建账户
	const accountDialogTitle = ref('') // 弹出层：创建账户
	const accountDialogTypeDisabled = ref(false) // 弹出层：账户分类按钮状态
	const accountDialogNameDisabled = ref(false) // 弹出层：账户名称状态
	const showDelete = ref(false) // 弹出层：删除按钮状态
	const accountDialogForm = ref({
		'id': 0,
		'name': '', // 账户名称
		'icon': '', // 账户图标
		'type': 1, // 账户类型 1 储蓄卡 2 信用卡
		'money': '0', // 账户余额
	}) // 弹出层：创建账户
	const myCalculator = ref(null) // 计算器组件
	const calculatorInitNumber = ref('0') // 计算器组件初始值
	const selectDialog = ref(null) // 选择器弹窗
	const selectDialog_Title = ref('选择银行图标') // 选择器弹窗标题
	const selectDialog_data = ref([]) // 选择器弹窗数据

	const account_type_list = [{
		label: '储蓄卡',
		value: 1
	}, {
		label: '信用卡',
		value: 2
	}] //账户类型列表

	onShow(() => {
		refreshPageData()
	})

	// 在组件卸载时
	onUnmounted(() => {});

	onBackPress(() => {
		if (accountDialog.value.showPopup) {
			// 中断页面返回事件
			return true;
		}
		// 继续返回事件
		return false;
	});

	// 下拉刷新
	onPullDownRefresh(() => {
		// 执行数据刷新逻辑
		refreshPageData(true)
	});

	// 刷新页面数据
	const refreshPageData = (neesStopPullDownRefresh = false) => {
		getChartData()
		getAccountList()
		// 停止下拉刷新动画
		if (neesStopPullDownRefresh) {
			uni.stopPullDownRefresh()
		}
	}

	// 获取图表数据
	const getChartData = () => {
		const monthObject = getAccountMoneyTotalForMonth()
		if (monthObject.list.length == 0) {
			account_total.value = '0'
			account_total_xy.value = '0'
			account_total_cx.value = '0'
			chartData.value = {}
			return
		}
		// 按时间正序排序
		monthObject.list.sort((a, b) => b.month < a.month ? 1 : -1);
		// 封装图表数据
		let categories = []
		let series_data = []
		let y_min = 0
		let y_max = 0
		for (const item of monthObject.list) {
			categories.push(Number.parseInt(item.month.slice(5, 7)))
			series_data.push(item.total)
			if (lt(item.total, 0)) {
				if (gt(negate(item.total), y_max)) {
					y_max = negate(item.total)
				}
			} else if (gt(item.total, y_max)) {
				y_max = item.total
			}
		}
		y_min = Number(negate(y_max))
		opts.value.yAxis.data[0].min = y_min
		opts.value.yAxis.data[0].max = y_max
		chartData.value = {
			'categories': categories,
			'series': [{
				'name': "净资产",
				'data': series_data
			}]
		}

		account_total.value = monthObject.currTotal.total
		account_total_xy.value = monthObject.currTotal.xyk_total
		account_total_cx.value = monthObject.currTotal.cxk_total
	}

	// 前往年度账单
	const goCashLogYear = () => {
		uni.navigateTo({
			url: '/pages/cash_log_year/cash-log-year'
		})
	}

	// 获取银行卡账户
	const getAccountList = () => {
		const accountList = getAllAccountList(0, 0)
		// 分类
		let list_1 = []
		let list_2 = []
		for (const item of accountList) {
			if (item.type == 1) {
				list_1.push(item)
			} else if (item.type == 2) {
				list_2.push(item)
			}
		}
		// 金额排序
		list_1.sort((a, b) => gt(b.money, a.money) ? 1 : -1)
		list_2.sort((a, b) => lt(b.money, a.money) ? 1 : -1)
		// 赋值
		account_list_1.value = list_1
		account_list_2.value = list_2
	}

	// 前往每日交易明细
	const goCashLogDay = () => {
		uni.navigateTo({
			url: '/pages/cash_log_day/cash-log-day'
		})
	}

	// 打开选择图标
	const openSelectDialog = () => {
		let list = getBankIconList()
		let bankIconList = []
		for (let item of list) {
			bankIconList.push({
				label: item.name,
				value: item.name,
				icon: item.icon,
			})
		}
		selectDialog_data.value = bankIconList
		selectDialog.value.open()
	}

	// 通用选择器：确认选择
	const confirmSelected = (item) => {
		accountDialogForm.value.icon = item.icon
		if (accountDialogForm.value.name == '') {
			accountDialogForm.value.name = item.value
		}
	}

	// 打开计算器
	const openCalculator = () => {
		myCalculator.value.open()
		calculatorInitNumber.value = accountDialogForm.value.money
	}

	// 计算器组件-取消计算
	const cancelCalculate = () => {
		// uni.showTabBar();
	}

	// 计算器组件-确认事件：计算结果 value
	const confirmCalculator = (value) => {
		// 这里只能正数，保存时，根据收支类型设置正负数;
		if (value.startsWith('-')) {
			value = value.slice(1)
		}
		accountDialogForm.value.money = value // 输入时不带正负，保存时添加正负
	}

	// 打开账户弹窗
	const openAccountDialog = (row) => {
		uni.hideTabBar();
		accountDialog.value.open()
		if (row) {
			let inputMoney = '0'
			// 输入时不带正负
			if (row.money.startsWith('-')) {
				inputMoney = row.money.slice(1)
			} else {
				inputMoney = row.money
			}
			accountDialogTitle.value = '修正账户金额'
			showDelete.value = true
			accountDialogTypeDisabled.value = true
			accountDialogNameDisabled.value = true
			accountDialogForm.value = {
				'id': row.id,
				'name': row.name, // 账户名称
				'type': row.type, // 账户类型 1 储蓄卡 2 信用卡
				'money': inputMoney, // 金额 (输入时不带正负，保存时添加正负), // 账户余额
				'icon': row.icon
			}
		} else {
			accountDialogTitle.value = '添加账户'
			showDelete.value = false
			accountDialogTypeDisabled.value = false
			accountDialogNameDisabled.value = false
			accountDialogForm.value = {
				'id': 0,
				'name': '', // 账户名称
				'type': 1, // 账户类型 1 储蓄卡 2 信用卡
				'money': '0', // 账户余额
				'icon': '/static/image/bank/yl.png'
			}
		}
	}

	// 保存账户
	const saveAccountData = () => {
		if (accountDialogForm.value.name.trim() == '') {
			uni.showToast({
				icon: 'none',
				title: '账户名称不能为空'
			})
			return
		}
		// 1 储蓄卡 2 信用卡
		if (accountDialogForm.value.type == 2 && gt(accountDialogForm.value.money, '0')) {
			accountDialogForm.value.money = '-' + accountDialogForm.value.money
		}
		if (accountDialogForm.value.type == 1 && lt(accountDialogForm.value.money, '0')) {
			accountDialogForm.value.money = accountDialogForm.value.money.slice(1)
		}
		// 默认图标
		if (accountDialogForm.value.icon == '') {
			accountDialogForm.value.icon = '/static/image/bank/yl.png'
		}

		let resultData = {}
		if (accountDialogForm.value.id == 0) {
			resultData = saveAccount(accountDialogForm.value.name, accountDialogForm.value.type,
				accountDialogForm.value.icon, accountDialogForm.value.money)
		} else {
			resultData = updateAccountTotalForName(accountDialogForm.value.name, accountDialogForm.value.icon,
				accountDialogForm.value.money)
		}
		if (!resultData.success) {
			uni.showToast({
				icon: 'none',
				title: resultData.msg
			})
			return
		}

		refreshPageData()
		accountDialog.value.close()
		uni.showTabBar();
	}

	// 取消保存
	const cancelSaveAccountData = () => {
		accountDialog.value.close()
		uni.showTabBar();
	}

	// 删除账户
	const delAccount = () => {
		let resultData = deleteAccount(accountDialogForm.value.id)
		if (!resultData.success) {
			uni.showToast({
				icon: 'none',
				title: resultData.msg
			})
			return
		}
		accountDialog.value.close()
		refreshPageData()
		uni.showTabBar();
	}
</script>

<style lang="scss">
	@import url("account.css");
</style>